#include <terrain.h>
#include <heightmap_bin.h>
#include <model.h>
#include <cmath>

void 
terrain::addDataSource(string heightmap, int offset_x, int offset_y) {
  item i;
   i.heightmap = heightmap;
   i.offset_x = offset_x;
   i.offset_y = offset_y;
  items.push_back(i);
}

bool
terrain::addToDB(model *_model, mysqlDatabase db) {

  FILE *fin = NULL;
  pngstream *pngs = NULL;

  for (iitem = items.begin(); iitem != items.end(); iitem++) {

    for (int level = _model->hm_levels - 1; level >= 0; level--) {

      if (fopen_s(&fin, iitem->heightmap.c_str(), "rb") != 0) {
        cerr << "File '" << iitem->heightmap << "' can't be opened" << endl;
        return false;
      }

      pngs = new pngstream();
      pngs->initializeInput(fin, true);

      heightmap_bin mybin;
      mybin.init(_model, pngs, level, iitem->offset_x, iitem->offset_y);
      while (pngs->hasNext()) {
        unsigned char *row = pngs->readLine();
        mybin.addRow(row);
      }

      pngs->finishInput();
      fclose(fin);
    }
  }

  return true;
}
